import { ref, onMounted, watch } from 'vue'
import { router } from '@/router/index'
import { useRoute } from 'vue-router' // 导入路由钩子
import myaxios from '@/auth/auth.service'
import { useHome } from '@/components/composables/useHome'
import {showToastMessage} from "@/utils/message"

// 定义组件状态类型
type ComponentState = 'loading' | 'loaded' | 'empty' | 'error'

export function useMainPage() {
  const currentPage = ref(1)
  const pageSize = ref(5)
  const searchKeyword = ref('')
  const relics = ref([])
  const total = ref(0)
  const totalPages = ref(0)
  const componentState = ref<ComponentState>('loading')
  const { choicesData } = useHome()
  const route = useRoute()
  const categoryname=route.query.categoryname
  const categoryid=route.query.categoryid

  // 加载数据函数
  const loadData = async (page = 1, search = '') => {
    try {
      componentState.value = 'loading'
      const routeId = route.query.categoryid // 路由参数中的id
      const params = {
        page,
        page_size: pageSize.value,
        search,
        category_id: routeId, // 添加当前路由的id到category_id
      }
      const response = await myaxios.fetchData(params)
      const data = response.data
      relics.value = data.data || []
      total.value = data.count || 0
      totalPages.value = data.pages || 0
      currentPage.value = page
      componentState.value = relics.value.length === 0 ? 'empty' : 'loaded'
      return true
    } catch (error) {
      console.error(`加载第${page}页数据失败:`, error)
      componentState.value = 'error'
      showToastMessage("error","数据加载失败，请重试")
      return false
    }
  }

  // 重新加载数据
  const reloadData = () => {
    console.log('用户触发数据重新加载')
    loadData(currentPage.value, searchKeyword.value)
  }

  // 处理搜索
  const handleSearch = () => {
    if (searchKeyword.value.trim() === '') {
      loadData(1, '')
    } else {
      loadData(1, searchKeyword.value.trim())
    }
  }

  // 图片加载错误处理
  const handleImageError = (relic: any) => {
    console.error(`图片加载失败: ${relic.image}`)
    if (!relic.imageErrorReported) {
      relic.imageErrorReported = true
    }
  }

  const getBuildingTypeText = (type: string, otherType: string) => {
    if (type === 'other') {
      return otherType.trim() || '其他'
    }
    const baseTypeText = choicesData.value.BUILDING_TYPE_CHOICES[type] || type

    return baseTypeText
  }

  const getDiseaseTypesText = (types: string, otherTypes: string) => {
    if (!types && !otherTypes) return '无'
    try {
      const typeCodes = types.split(',').filter((code) => code.trim() !== '')
      const displayTypes = typeCodes
        .map((code) => {
          const typeText = choicesData.value.DISEASE_CHOICES[code] || code
          return typeText === '其他' ? '' : typeText
        })
        .filter((type) => type !== '')
      const hasOther = typeCodes.includes('other')
      let customTypes: string[] = []
      if (hasOther && otherTypes && otherTypes.trim() !== '') {
        customTypes = otherTypes.split(',').filter((type) => type.trim() !== '')
      }
      const allTypes = [...displayTypes, ...customTypes].filter((type) => type !== '')
      return allTypes.length > 0 ? allTypes.join('、') : '无'
    } catch {
      const allTypes = [types, otherTypes].filter((t) => t && t.trim() !== '').join('、')
      return allTypes || '无'
    }
  }

  // 初始化数据
  const initData = async () => {
    console.log('初始化页面数据...')
    currentPage.value = 1
    searchKeyword.value = ''
    relics.value = []
    total.value = 0
    totalPages.value = 0
    await loadData(1)
  }

  onMounted(async () => {
    console.log('组件挂载，初始化数据...')
    await initData()
  })

  watch(currentPage, (newPage, oldPage) => {
    if (newPage !== oldPage) {
      loadData(newPage, searchKeyword.value.trim())
    }
  })

  const goToEdit = (id: number) => {
    router.push(`/edit/${id}`)
  }

  // 删除文物
  const deleteRelic = async (id: number) => {
    if (!window.confirm('确定要删除该文物吗？此操作不可恢复')) {
      return
    }
    try {
      await myaxios.deleteRelic(id)
      showToastMessage("success","删除成功")
      router.push({
      path: '/mainpage',
      query: {
        categoryid: route.query.categoryid, // 传递参数，无需在路径中定义
        categoryname:route.query.categoryname  },
    })
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    } catch (error) {
      console.error('删除失败:', error)
      showToastMessage("error","删除失败，请重试")
    }
  }

  // 返回上一页
  const goBack = () => {
    console.log('返回上一页')
    router.go(-1)
  }

  const goToUpload = () => {
    router.push({
      path: '/upload',
      query: {
        categoryid: route.query.categoryid, // 传递参数，无需在路径中定义
        categoryname:route.query.categoryname
      },
    })
  }
  const goToUser = () => {
    router.push('/personalinfo')
  }
  const goToCategory = () => {
    router.push('/category')
  }

  const goHome = () => {
    router.push('/category')
  }
  const goToDetail = (id: number) => {
    router.push(`/relic-detail/${id}`)
  }

    const goToMainPage = (categoryId: number, categoryName: string) => {
    router.push({
      path: '/mainpage/',
      query: { categoryid: categoryId, categoryname: categoryName },
    })
  }
  // 病害图片加载错误处理
  const handleDiseaseImageError = (row) => {
    console.error('病害图片加载失败:', row.id)
    // 可以添加病害图片加载失败后的处理逻辑
  }

  // 页码变化处理
  const handlePageChange = (page) => {
    currentPage.value = page
  }

  // 每页数量变化处理
  const handlePageSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1 // 重置为第一页
    loadData()
  }

  // 日期格式化
  // 格式化日期
  const formatDate = (dateString: string) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }
  return {
    currentPage,
    pageSize,
    searchKeyword,
    relics,
    total,
    totalPages,
    componentState,
    categoryid,
    categoryname,
    loadData,
    reloadData,
    handleSearch,
    handleImageError,
    getBuildingTypeText,
    getDiseaseTypesText,
    initData,
    goToUser,
    goHome,
    goToCategory,
    goToMainPage,
    goToEdit,
    deleteRelic,
    goBack,
    goToUpload,
    goToDetail,
    handlePageSizeChange,
    handlePageChange,
    formatDate,
    handleDiseaseImageError,
  }
}
